import myStorage from '@/utils/myStorage.js'
export function tranObjToZip(projectObj, cb) {
    console.log(JSON.stringify(projectObj));
    plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function (fs) {
        // 创建项目文件夹
        fs.root.getDirectory('_doc/' + projectObj.name, { create: true }, function (DEntry) {
            console.log('创建项目文件夹' + projectObj.name + '成功');
            // 文件夹和图片全部创建成功的回调，生成压缩文件
            var endCallBack = function (projectObj, cb) {
                const targetPath = '_doc/' + projectObj.name + '/';
                const zipfile = '_doc/' + projectObj.name + '.zip';
                plus.zip.compress(targetPath, zipfile, function () {
                    console.log('文件生成完毕');
                    if (cb) {
                        cb();
                    }
                }, errHandler);
            }
            // 循环遍历创建一级分类文件夹
            createLevel1(0, projectObj, DEntry, () => { endCallBack(projectObj, cb); });
        }, errHandler);
    }, errHandler);
}
// 创建一级分类文件夹
function createLevel1(level1Index, projectObj, DEntry, createLevel1EndCallBack) {
    if (level1Index >= projectObj.level1list.length) {
        if (createLevel1EndCallBack) {
            createLevel1EndCallBack();
        }
        return;
    }
    let level1Obj = projectObj.level1list[level1Index] || {};
    DEntry.getDirectory('一级分类-' + level1Obj.level1, { create: true }, function (DEntry1) {
        console.log('创建一级分类' + level1Obj.level1 + '成功');
        // 一级分类有照片描述，那么创建照片描述
        if (level1Obj.photolist && level1Obj.photolist.length > 0) {
            const pathName = '_doc/' + projectObj.name + '/一级分类-' + level1Obj.level1;
            createPhoto(0, level1Obj.photolist, DEntry1, pathName, () => {
                // 照片描述创建完毕，有二级分类那么就创建二级分类
                if (level1Obj.level2list && level1Obj.level2list.length > 0) {
                    createLevel2(0, projectObj, level1Obj, DEntry1, () => {
                        createLevel1(level1Index + 1, projectObj, DEntry, createLevel1EndCallBack);
                    });
                } else {
                    // 没有二级分类，创建下一个一级分类
                    createLevel1(level1Index + 1, projectObj, DEntry, createLevel1EndCallBack);
                }
            });
        } else {
            // 没有照片描述，有二级分类那么就创建二级分类
            if (level1Obj.level2list && level1Obj.level2list.length > 0) {
                createLevel2(0, projectObj, level1Obj, DEntry1, () => {
                    createLevel1(level1Index + 1, projectObj, DEntry, createLevel1EndCallBack);
                });
            } else {
                // 没有二级分类，创建下一个一级分类
                createLevel1(level1Index + 1, projectObj, DEntry, createLevel1EndCallBack);
            }
        }
    }, errHandler);
}

function createLevel2(level2Index, projectObj, level1Obj, DEntry1, createLevel2EndCallBack) {
    if (level2Index >= level1Obj.level2list.length) {
        if (createLevel2EndCallBack) {
            createLevel2EndCallBack();
        }
        return;
    }
    let level2Obj = level1Obj.level2list[level2Index] || {};
    DEntry1.getDirectory('二级分类-' + level2Obj.level2, { create: true }, function (DEntry2) {
        console.log('创建二级分类' + level2Obj.level2 + '成功');
        // 二级分类有照片描述，那么创建照片描述
        if (level2Obj.photolist && level2Obj.photolist.length > 0) {
            const pathName = '_doc/' + projectObj.name + '/一级分类-' + level1Obj.level1 + '/二级分类-' + level2Obj.level2;
            createPhoto(0, level2Obj.photolist, DEntry2, pathName, () => {
                // 照片描述创建完毕，循环创建下一个二级分类
                createLevel2(level2Index + 1, projectObj, level1Obj, DEntry1, createLevel2EndCallBack);
            });
        } else {
            // 没有照片描述，直接创建下一个二级分类
            createLevel2(level2Index + 1, projectObj, level1Obj, DEntry1, createLevel2EndCallBack);
        }
    }, errHandler);
}

function createPhoto(photoIndex, list, DEntry, basePath, createPhotoEndCallBack) {
    if (photoIndex >= list.length) {
        if (createPhotoEndCallBack) {
            createPhotoEndCallBack();
        }
        return;
    }
    let obj = list[photoIndex];
    DEntry.getDirectory('照片描述-' + obj.label, { create: true }, function () {
        console.log('创建照片描述' + obj.label + '成功')
        if (obj.list && obj.list.length > 0) {
            createImage(0, obj, basePath);
        }
        createPhoto(photoIndex + 1, list, DEntry, basePath, createPhotoEndCallBack);
    }, errHandler);
}

function createImage(imgIndex, obj, path, endCallBack) {
    if (imgIndex >= obj.list.length) {
        if (endCallBack) {
            endCallBack();
        }
        return;
    }
    let obj1 = obj.list[imgIndex];
    const mimeObj = {
        'image/x-ms-bmp': '.bmp',
        'image/jpeg': '.jpg',
        'image/gif': '.gif',
        'image/png': '.png',
        'image/tiff': '.tiff',
        'image/x-targa': '.tga',
        'image/vnd.adobe.photoshop': '.psd'
    }
    var base64 = myStorage.getItem(obj1.item);
    let arr = base64.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let filePath = path + '/照片描述-' + obj.label + '/' + obj.label + '-' + imgIndex + mimeObj[mime];
    var bitmap = new plus.nativeObj.Bitmap("test");
    bitmap.loadBase64Data(base64, function () {
        bitmap.save(filePath, { overwrite: true, quality: 20 }, function () {
            createImage(imgIndex + 1, obj, path);
        });
    }, errHandler)
}

function errHandler(err) {
    console.log(err);
}

// base64转blob
export function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
// blob转file
export function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}
// 获取base64大小
function getImgSize(base64url) {
    //获取base64图片大小，返回KB数字
    var str = base64url.split(',')[1];//这里根据自己上传图片的格式进行相应修改
    var strLength = str.length;
    var fileLength = parseInt(strLength - (strLength / 8) * 2);
    // 由字节转换为KB
    var size = "";
    size = (fileLength / 1024).toFixed(2);
    return parseInt(size);
}
// base64图片使用canvas压缩, 开放了压缩限制，目前压缩为原大小的1/3;
export function compressImageCanvas(base64, callback) {
    console.log(getImgSize(base64));
    var img = new Image();
    img.src = base64;
    img.onload = function () {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        // 图片原始尺寸
        var originWidth = this.width;
        var originHeight = this.height;
        var maxWidth = 2000;
        var targetWidth = originWidth;
        var targetHeight = originHeight;
        if (originWidth > maxWidth) {
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        }
        // canvas对图片进行缩放
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight);
        // 图片压缩
        context.drawImage(img, 0, 0, targetWidth, targetHeight);
        var newUrl = canvas.toDataURL('image/jpeg', 0.8);
        console.log(getImgSize(newUrl));
        if (callback) {
            callback(newUrl);
        }
    }
}
